package com.diamondparking.action;

import com.diamondparking.model.Employee;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.framework.EntityController;

@Stateful
@Name("authenticator")
public class AuthenticatorBean extends EntityController implements Authenticator {

    @Out(required = false, scope = ScopeType.SESSION)
    private long currentEmployeeId;

    public boolean authenticate() {
        try {
            Employee employee = getMember(getIdentity().getUsername(), getIdentity().getPassword());            
            currentEmployeeId = employee.getId();
            info(getMessages().get("com.diamondparking.EMPLOYEE_AUTHENTICATED"));
            return true;
        } catch (NoResultException nre) {
            info(getMessages().get("com.diamondparking.EMPLOYEE_FAILED_AUTHENTICATION"));
            return false;
        } catch (NonUniqueResultException nure) {
            fatal(getMessages().get("com.diamondparking.EMPLOYEE_AUTHENTICATION_FATAL_ERROR"));
            return false;
        }
    }
    
    private Employee getMember(String username, String password) {
        return (Employee) createNamedQuery("Employee.authenticate")
                .setParameter("username", username)
                .setParameter("password", password)
                .getSingleResult();
    }
    
    @Destroy
    @Remove
    public void destroy() {
    }
}
